import { reactive } from 'vue';
import { FormItemValidate, FormRules } from '@/utils/types';

export interface RegisterForm {
  username: string;
  email: string;
  password: string;
  confirm: string;
}

export interface UseRegisterForm {
  registerForm: RegisterForm;
  registerRules: FormRules;
}

export const useRegisterForm = (): UseRegisterForm => {
  const registerForm = reactive({
    username: 'admin',
    email: 'idaijunming@163.com',
    password: '123456',
    confirm: '123456',
  }) as RegisterForm;

  const validateUsername: FormItemValidate = (rule, value, callback) => {
    if (value.trim().length === 0) {
      callback(new Error('请输入用户名'));
    } else {
      callback();
    }
  };
  const validateEmail: FormItemValidate = (rule, value, callback) => {
    if (value.trim().length === 0) {
      callback(new Error('请输入邮箱'));
    } else if (/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(value.trim())) {
      callback();
    } else {
      callback(new Error('请输入正确格式的邮箱!'));
    }
  };
  const validatePassword: FormItemValidate = (rule, value, callback) => {
    if (value.length < 6) {
      callback(new Error('密码长度不能小于6位!'));
    } else {
      callback();
    }
  };

  const validateConfirm: FormItemValidate = (rule, value, callback) => {
    if (value.length < 6) {
      callback(new Error('密码长度不能小于6位!'));
    } else if (value !== registerForm.password) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      callback();
    }
  };

  const registerRules = reactive({
    username: [{ required: true, trigger: 'blur', validator: validateUsername }],
    email: [{ required: true, trigger: 'blur', validator: validateEmail }],
    password: [{ required: true, trigger: 'blur', validator: validatePassword }],
    confirm: [{ required: true, trigger: 'blur', validator: validateConfirm }],
  });

  return {
    registerForm,
    registerRules,
  };
};
